<script setup lang="ts">
import { ref, onMounted, computed, h } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import Upload from "@iconify-icons/ep/upload";
import EditPen from "@iconify-icons/ep/edit-pen";
import { ElTag } from "element-plus";
import {
  getMaterialSelect,
  getVideoList,
  getDirectorList,
  getEditorList,
  type MaterialItem,
  type VideoListParams,
  type MaterialSelectResponse,
  type UserListResponse
} from "@/api/material";
import { getAdAccounts } from "@/api/promotion";
import type { TableColumnCtx } from "element-plus";
import UploadDialog from "./components/UploadDialog.vue";
import BatchEditDialog from "./components/EditDialog.vue";

defineOptions({
  name: "MaterialCenter"
});

const formRef = ref();
const tableRef = ref();

const form = ref<VideoListParams>({
  name: "",
  editor: undefined,
  state: undefined,
  adAccountIdList: [],
  page: 1,
  size: 10
});

const loading = ref(false);
const dataList = ref<MaterialItem[]>([]);
const enumOptions = ref<MaterialSelectResponse>({
  audioLabel: [],
  auditState: [],
  videoLabel: []
});

const directorOptions = ref<UserListResponse["list"]>([]);
const editorOptions = ref<UserListResponse["list"]>([]);
const adAccountsOptions = ref<{ adAccountId: number; adAccountName: string }[]>(
  []
);

const uploadDialogVisible = ref(false);
const batchEditDialogVisible = ref(false);
const selectedItems = ref<MaterialItem[]>([]);

const hasSelectedItems = computed(() => selectedItems.value.length > 0);

// 新增视频预览相关的状态
const videoDialogVisible = ref(false);
const videoUrl = ref("");

// 在 script setup 部分添加以下内容
const videoRef = ref<HTMLVideoElement | null>(null);

// 获取枚举数据
const fetchEnumOptions = async () => {
  try {
    const res = await getMaterialSelect();
    console.log("枚举数据响应:", res); // 添加日志查看响应数据
    if (res) {
      enumOptions.value = res;
    }
    form.value.state = res.auditState[0].value;
  } catch (error) {
    console.error("获取枚举数据失败:", error);
  }
};

const fetchDirectorOptions = async () => {
  try {
    const res = await getDirectorList();
    console.log("编导数据响应:", res);
    if (res) {
      directorOptions.value = res.list || [];
    }
  } catch (error) {
    console.error("获取枚举数据失败:", error);
  }
};

const fetchEditorOptions = async () => {
  try {
    const res = await getEditorList();
    console.log("剪辑数据响应:", res);
    if (res) {
      editorOptions.value = res.list || [];
    }
  } catch (error) {
    console.error("获取枚举数据失败:", error);
  }
};

const fetchAdAccountsOptions = async () => {
  try {
    const res = await getAdAccounts();
    console.log("广告账户数据响应:", res);
    if (res) {
      adAccountsOptions.value = res || [];
    }
  } catch (error) {
    console.error("获取枚举数据失败:", error);
  }
};

const formatState = (state: number) => {
  const statusMap = {
    "-1": { text: "已提交", type: "info" },
    0: { text: "已提交", type: "info" },
    1: { text: "已上传", type: "warning" },
    2: { text: "审核成功", type: "success" },
    9: { text: "审核失败", type: "danger" }
  };

  const statusInfo = statusMap[state] || { text: "未知", type: "info" };
  return h(ElTag, { type: statusInfo.type }, () => statusInfo.text);
};

const columns = ref([
  {
    type: "selection",
    width: 55,
    align: "left",
    hide: false,
    label: "选择"
  },
  {
    label: "素材名称",
    prop: "materialName",
    width: 200,
    slot: ""
  },
  {
    label: "素材预览",
    prop: "coverUrl",
    slot: "preview"
  },
  {
    label: "视频模式",
    prop: "materialMode",
    slot: "",
    formatter: (
      row: MaterialItem,
      column: TableColumnCtx<MaterialItem>,
      cellValue: number
    ) => (cellValue === 1 ? "竖版" : "横版")
  },
  {
    label: "编导",
    prop: "directorName",
    slot: ""
  },
  {
    label: "剪辑师",
    prop: "editorName",
    slot: ""
  },
  {
    label: "状态",
    prop: "state",
    slot: "",
    formatter: (row: any) => formatState(row.state)
  },
  {
    label: "音频语言",
    prop: "audioLanguageTag",
    slot: "",
    formatter: (
      row: MaterialItem,
      column: TableColumnCtx<MaterialItem>,
      cellValue: string
    ) => {
      const label = enumOptions.value?.audioLabel?.find(
        item => item.value === cellValue
      );
      return label?.key || cellValue;
    }
  },
  {
    label: "视频语言",
    prop: "footageLanguageTag",
    slot: "",
    formatter: (
      row: MaterialItem,
      column: TableColumnCtx<MaterialItem>,
      cellValue: string
    ) => {
      const label = enumOptions.value?.videoLabel?.find(
        item => item.value === cellValue
      );
      return label?.key || cellValue;
    }
  },
  {
    label: "上传时间",
    prop: "createTime",
    width: 180,
    slot: ""
  },
  {
    label: "广告账户",
    prop: "accountName",
    slot: ""
  }
]);

const pagination = ref({
  total: 0,
  pageSize: 10,
  currentPage: 1
});

// 获取视频列表数据
const fetchVideoList = async () => {
  try {
    loading.value = true;
    const params: VideoListParams = {
      ...form.value,
      state: Number(form.value.state),
      page: pagination.value.currentPage,
      size: pagination.value.pageSize
    };
    const res = await getVideoList(params);
    console.log("视频列表响应:", res); // 添加日志查看响应数据
    if (res) {
      dataList.value = res.list;
      pagination.value.total = res.total;
    }
  } catch (error) {
    console.error("获取视频列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  fetchVideoList();
};

const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  fetchVideoList();
};

const onSearch = () => {
  pagination.value.currentPage = 1;
  fetchVideoList();
};

const resetForm = (formEl: any) => {
  if (!formEl) return;
  formEl.resetFields();
  form.value.state = Number(enumOptions.value.auditState[0].value);
  onSearch();
};

const handleUpload = () => {
  uploadDialogVisible.value = true;
};

const handleUploadSuccess = () => {
  fetchVideoList();
};

const handleEditSuccess = () => {
  fetchVideoList();
};

const handleBatchEdit = () => {
  if (!hasSelectedItems.value) {
    return;
  }
  batchEditDialogVisible.value = true;
};

const handleSelectionChange = (selection: MaterialItem[]) => {
  selectedItems.value = selection;
  console.log("Selected items:", selectedItems.value);
};

// 预览视频的方法
const handlePreviewVideo = (row: MaterialItem) => {
  if (row.videoUrl) {
    videoUrl.value = row.videoUrl;
    videoDialogVisible.value = true;
  }
  // if (row.videoUrl) {
  //   videoUrl.value = row.videoUrl;
  //   videoDialogVisible.value = true;
  // }
};

// 处理视频对话框关闭
const handleVideoDialogClose = () => {
  if (videoRef.value) {
    videoRef.value.pause();
    videoRef.value.currentTime = 0;
  }
  videoUrl.value = "";
};

onMounted(async () => {
  await fetchEnumOptions();
  fetchDirectorOptions();
  fetchEditorOptions();
  fetchAdAccountsOptions();
  fetchVideoList();
});
</script>

<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item prop="name" label="素材名称">
        <el-input
          v-model="form.name"
          placeholder="请输入素材名称"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item prop="director" label="编导">
        <el-select
          v-model="form.director"
          placeholder="请选择编导"
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in directorOptions"
            :key="Number(item.accountId)"
            :label="item.nickName"
            :value="item.accountId"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="editor" label="剪辑">
        <el-select
          v-model="form.editor"
          placeholder="请选择剪辑"
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in editorOptions"
            :key="Number(item.accountId)"
            :label="item.nickName"
            :value="item.accountId"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="state" label="状态">
        <el-select
          v-model="form.state"
          placeholder="请选择状态"
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in enumOptions.auditState"
            :key="Number(item.value)"
            :label="item.key"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="adAccountId" label="广告账户">
        <el-select
          v-model="form.adAccountIdList"
          placeholder="请选择广告账户"
          clearable
          filterable
          multiple
          collapse-tags
          class="!w-[220px]"
        >
          <el-option
            v-for="item in adAccountsOptions"
            :key="item.adAccountId"
            :label="item.adAccountName"
            :value="item.adAccountId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>

    <PureTableBar :columns="columns" @refresh="onSearch">
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(EditPen)"
          :disabled="!hasSelectedItems"
          @click="handleBatchEdit"
        >
          批量编辑
        </el-button>
        <el-button
          type="primary"
          :icon="useRenderIcon(Upload)"
          @click="handleUpload"
        >
          上传素材
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :size="size"
          adaptive
          height="1050"
          :adaptiveConfig="{ offsetBottom: 80 }"
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
          @selection-change="handleSelectionChange"
        >
          <template #preview="{ row }">
            <div
              class="w-[120px] h-[80px] bg-bg_color flex items-center justify-center relative group cursor-pointer"
              @click="handlePreviewVideo(row)"
            >
              <img
                v-if="row.coverUrl"
                :src="`${row.coverUrl}?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto`"
                class="w-full h-full object-cover"
                alt="预览图"
              />
              <el-icon v-else><VideoPlay /></el-icon>
              <div
                v-if="row.videoUrl"
                class="absolute inset-0 bg-black bg-opacity-50 hidden group-hover:flex items-center justify-center"
              >
                <div class="text-white text-2xl">
                  <el-icon><VideoPlay /></el-icon>
                </div>
              </div>
            </div>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <UploadDialog
      v-model:visible="uploadDialogVisible"
      :enum-options="enumOptions"
      :director-options="directorOptions"
      :editor-options="editorOptions"
      :ad-accounts-options="adAccountsOptions"
      @success="handleUploadSuccess"
    />

    <BatchEditDialog
      v-model:visible="batchEditDialogVisible"
      :director-options="directorOptions"
      :editor-options="editorOptions"
      :selected-item-ids="selectedItems.map(item => item.id)"
      @success="handleEditSuccess"
    />

    <!-- 视频预览对话框 -->
    <el-dialog
      v-model="videoDialogVisible"
      width="auto"
      :show-close="false"
      :center="true"
      :align-center="true"
      :close-on-click-modal="true"
      @close="handleVideoDialogClose"
    >
      <video
        v-if="videoUrl"
        ref="videoRef"
        :src="videoUrl"
        controls
        style="max-width: 80vw; max-height: 80vh"
      />
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
